package com.vehicle.repair.service;

import com.vehicle.repair.model.Feedback;
import com.vehicle.repair.model.WorkOrder;
import com.vehicle.repair.repository.FeedbackRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

@Service
@Transactional
public class FeedbackService {
    private final FeedbackRepository feedbackRepository;
    private final WorkOrderService workOrderService;

    public FeedbackService(FeedbackRepository feedbackRepository,
                         WorkOrderService workOrderService) {
        this.feedbackRepository = feedbackRepository;
        this.workOrderService = workOrderService;
    }

    public Feedback addFeedback(Feedback feedback, Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        
        if (order.getStatus() != WorkOrder.OrderStatus.已完成) {
            throw new IllegalStateException("Feedback can only be added to completed orders");
        }
        
        feedback.setOrder(order);
        return feedbackRepository.save(feedback);
    }

    public Optional<Feedback> getFeedbackById(Integer id) {
        return feedbackRepository.findById(id);
    }

    public Optional<Feedback> getFeedbackByOrder(Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        return feedbackRepository.findByOrder(order);
    }

    public void deleteFeedback(Integer id) {
        feedbackRepository.deleteById(id);
    }

    public double getAverageRating() {
        return feedbackRepository.findAll()
                .stream()
                .mapToInt(Feedback::getRating)
                .average()
                .orElse(0.0);
    }
}
